//
//  OPKStoreManager.m
//  PaymentDemo
//
//  Created by ycgame on 2020/4/21.
//  Copyright © 2020 maqianzheng. All rights reserved.
//

#import "OPKStoreManager.h"
#import "OPKConfiguration.h"

@interface OPKStoreManager()<SKRequestDelegate, SKProductsRequestDelegate>
@property (strong) SKProductsRequest *productRequest;
@end

@implementation OPKStoreManager

+ (OPKStoreManager *)sharedInstance {
    static dispatch_once_t onceToken;
    static OPKStoreManager * storeManagerSharedInstance;

    dispatch_once(&onceToken, ^{
        storeManagerSharedInstance = [[OPKStoreManager alloc] init];
    });
    return storeManagerSharedInstance;
}

- (instancetype)init {
    self = [super init];

    if (self != nil) {
        _products = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}

#pragma mark - Request Information

/// 开始请求商品
-(void)startProductRequestWithIdentifiers:(NSArray *)identifiers {
    [self fetchProductsMatchingIdentifiers:identifiers];
}

/// 获取商品
-(void)fetchProductsMatchingIdentifiers:(NSArray *)identifiers {
    // 创建商品id集合
    NSSet *productIdentifiers = [NSSet setWithArray:identifiers];

    // 初始化 productRequest
    self.productRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    self.productRequest.delegate = self;

    // 发送请求
    [self.productRequest start];
}

#pragma mark SKProductsRequestDelegate

- (void)productsRequest:(nonnull SKProductsRequest *)request didReceiveResponse:(nonnull SKProductsResponse *)response {
    if (self.products.count > 0) {
        [self.products removeAllObjects];
    }
    
    if ((response.products).count > 0) {
        self.products = [NSMutableArray arrayWithArray:response.products];
    }
    
    if (self.products.count > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:OPKProductRequestNotification object:self];
        });
    }
}

@end
